<template>
    <div class="lock-screen-container">
        <!-- 核心弹窗 -->
        <div class="lock-modal">
            <!-- 标题区域 -->
            <div class="title-group">
                <div class="lock-status">当前是锁屏状态</div>
                <div class="welcome-text">欢迎回来</div>
            </div>
            <el-form :model="form" :rules="validationRules" ref="formRef" label-width="0px" class="lock-form"
                @submit.prevent="handleUnlock">
                <el-form-item prop="password" class="password-item">
                    <el-input v-model="form.password" type="password" placeholder="请输入密码" size="large"
                        @keyup.enter="handleUnlock" @focus="handleInputFocus">
                        <template #prefix>
                            <el-icon class="lock-icon">
                                <EleLock />
                            </el-icon>
                        </template>
                    </el-input>
                </el-form-item>

                <el-form-item class="submit-item">
                    <el-button type="primary" class="unlock-btn" @click="handleUnlock" :loading="loading">
                        解锁进入系统
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script setup lang="ts" name="LockScreen">
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { Lock as EleLock } from '@element-plus/icons-vue';
import { Session } from '/@/utils/storage';

const router = useRouter();
const formRef = ref<FormInstance | null>(null);
const loading = ref(false);
const form = reactive({
    password: ''
});

// 检查登录状态和状态一致性
const checkAuthAndConsistency = (): boolean => {
    const isAuthenticated = Session.get('isAuthenticated');
    const isLocked = localStorage.getItem('isLocked') === 'true';

    // 关键修复：如果未登录但处于锁屏状态，清除状态并跳转登录
    if (!isAuthenticated && isLocked) {
        localStorage.removeItem('isLocked');
        localStorage.removeItem('attemptedPath');
        ElMessage.warning('请先登录');
        router.replace('/login');
        return false;
    }

    if (!isAuthenticated) {
        ElMessage.warning('请先登录');
        router.replace('/login');
        return false;
    }
    return true;
};

// 输入框聚焦时清除错误提示
const handleInputFocus = () => {
    formRef.value?.clearValidate('password');
};

// 验证规则
const validationRules = reactive<FormRules>({
    password: [
        {
            required: true,
            message: '请填写密码',
            trigger: ['blur', 'change']
        },
        {
            min: 6,
            max: 18,
            message: '密码格式错误（6-18位）',
            trigger: ['blur', 'change']
        },
        {
            validator: async (rule, value, callback) => {
                const trimmedVal = value?.trim() || '';
                if (!trimmedVal) {
                    return callback(new Error('请输入密码'));
                }

                const storedPwd = Session.get('loginPassword');
                console.log('登录时存储的密码:', storedPwd);
                console.log('当前输入的密码:', trimmedVal);

                if (!storedPwd) {
                    return callback(new Error('未找到密码信息，请重新登录'));
                }

                if (trimmedVal === storedPwd) {
                    callback();
                } else {
                    callback(new Error('密码错误请重新输入'));
                }
            },
            trigger: 'blur'
        }
    ]
});

// 解锁逻辑
const handleUnlock = async (event?: Event) => {
    // 如果是事件对象，阻止默认行为
    if (event && event.preventDefault) {
        event.preventDefault();
    }

    if (!formRef.value) return;

    // 检查登录状态和状态一致性
    if (!checkAuthAndConsistency()) return;

    try {
        loading.value = true;
        await formRef.value.validate();

        // 验证通过，清除锁屏状态
        localStorage.removeItem('isLocked');
        const redirectPath = localStorage.getItem('attemptedPath') || '/';
        localStorage.removeItem('attemptedPath');

        ElMessage.success('解锁成功');
        router.replace(redirectPath);
        formRef.value?.resetFields();
    } catch (error) {
        console.log('表单验证失败:', error);
    } finally {
        loading.value = false;
    }
};

// 禁止浏览器后退
const preventBack = (event: PopStateEvent) => {
    if (localStorage.getItem('isLocked') === 'true') {
        // 阻止浏览器后退
        history.pushState(null, '', router.currentRoute.value.fullPath);
        event.preventDefault();
        event.stopPropagation();
    }
};

// 页面加载时自动聚焦输入框
onMounted(() => {
    // 检查登录状态和状态一致性
    if (!checkAuthAndConsistency()) return;

    // 添加历史记录，防止后退
    history.pushState(null, '', router.currentRoute.value.fullPath);

    // 监听 popstate 事件
    window.addEventListener('popstate', preventBack);

    setTimeout(() => {
        const input = document.querySelector('.password-item input') as HTMLInputElement;
        if (input) input.focus();

        console.log('sessionStorage中的loginPassword:', Session.get('loginPassword'));
    }, 100);
});

// 组件卸载时移除事件监听
onUnmounted(() => {
    window.removeEventListener('popstate', preventBack);
});
</script>

<style scoped lang="scss">
// 全局容器
.lock-screen-container {
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f0f7fd;
    background-image:
        radial-gradient(circle at 20% 30%, rgba(68, 135, 236, 0.05) 0%, transparent 20%),
        radial-gradient(circle at 80% 70%, rgba(68, 135, 236, 0.05) 0%, transparent 20%);
}

// 弹窗容器
.lock-modal {
    width: 360px;
    height: 420px;
    background: white;
    border-radius: 15px;
    padding: 50px 35px;
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
}

// 标题组
.title-group {
    text-align: center;
    margin-bottom: 45px;
}

.lock-status {
    font-size: 26px;
    font-weight: 600;
    color: #505050;
    margin-bottom: 8px;
    letter-spacing: 0.5px;
}

.welcome-text {
    font-size: 18px;
    color: #888;
    font-weight: 400;
}

// 表单样式
.lock-form {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
}

// 密码输入项
.password-item {
    margin-bottom: 25px !important;
}

:deep(.el-input) {
    &.el-input--large .el-input__wrapper {
        height: 42px;
        border-radius: 6px;
        border: 1.5px solid #D0D4DB;
        transition: all 0.3s ease;
    }

    .el-input__wrapper {
        &:hover {
            border-color: #4487EC;
        }

        &:focus-within {
            border-color: #4487EC;
            box-shadow: 0 0 0 3px rgba(68, 135, 236, 0.1);
            outline: none;
        }
    }

    .el-input__placeholder {
        color: #B0B0B0;
        font-size: 14px;
    }
}

// 锁图标
.lock-icon {
    color: #999;
    font-size: 18px;
    margin-right: 8px;
}

// 错误提示
:deep(.el-form-item__error) {
    font-size: 12px;
    color: #F56C6C;
    margin-top: 6px;
    position: static;
    line-height: 1.4;
}

// 提交按钮项
.submit-item {
    margin-bottom: 0 !important;
}

// 解锁按钮
.unlock-btn {
    width: 100%;
    height: 42px;
    background-color: #4487EC;
    color: white;
    border: none;
    border-radius: 6px;
    font-size: 16px;
    font-weight: 500;
    transition: all 0.3s ease;
    letter-spacing: 0.5px;

    &:hover,
    &:focus {
        background-color: #3A7BD5;
        box-shadow: 0 4px 12px rgba(68, 135, 236, 0.2);
    }

    &:active {
        transform: translateY(1px);
        box-shadow: none;
    }
}

// 加载状态调整
:deep(.el-button--loading .el-loading-spinner) {
    margin-right: 8px;
}

// 响应式适配
@media (max-width: 375px) {
    .lock-modal {
        width: 92%;
        height: auto;
        min-height: 380px;
        padding: 40px 25px;
    }

    .title-group {
        margin-bottom: 35px;
    }

    .lock-status {
        font-size: 24px;
    }
}
</style>